<?php
/**
 * Created by PhpStorm.
 * User: jinji
 * Date: 2017/10/25
 * Time: 22:24
 */

namespace App\Services;


use App\Model\Category;
use App\Model\Meta;
use Illuminate\Support\Facades\DB;

class CategoryService
{
    /**
     * 得到节点id的所有子节点
     * @param $id
     * @return array
     */
    public function getChilds($id)
    {
        $categorys = Category::all();
        $ids = $this->treeIds($categorys,$id);
        return $ids;
    }

    private function treeIds($data, $pId)
    {
        static $ids = [];
        foreach ($data as $k => $v) {
            if ($v['parent'] == $pId) {
                $ids[] = $v['id'];
                $v['children'] = $this->treeIds($data, $v['id']);
            }
        }
        return $ids;
    }

    public static function CateCounts($type)
    {
        return (new Category())->where('type',$type)->count();
    }

    public function countUsed($page,$type)
    {
        $meta = Meta::where('page_id',$page->id)->first();
        $categorys = array();
        if($type == Category::TYPE_TAG){
            $categorys = $meta->tags;
        }elseif($type == Category::TYPE_CATE){
            $categorys = $meta->categorys;
        }
        $cc = json_decode($categorys,true);
        if(count($cc) === 0){
            return false;
        }
        $params = array();
        foreach($cc as $c){
            $cate = Category::where('id',$c)->first();
            $cate->frequency = $cate->frequency + 1;
            $cate->save();
        }
        return true;
    }

    public static function cates()
    {
        $cates = Category::where('type',Category::TYPE_CATE)->where('level',1)->get();
        return $cates;
    }
}